<?php

namespace app\admin\model;

use think\Model;
use think\Cache;

class Cate extends Model
{
    // 表名
    protected $name = 'cate';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'status_text'
    ];

    // 定义字段类型
    protected $type = [
        'id' => 'integer',
        'pid' => 'integer',
        'sort' => 'integer',
        'status' => 'integer',
        'createtime' => 'integer',
        'updatetime' => 'integer',
    ];

    // 设置字段信息
    protected $schema = [
        'id' => 'int',
        'pid' => 'int',
        'name' => 'string',
        'sort' => 'int',
        'rules' => 'string',
        'url' => 'string',
        'createtime' => 'int',
        'updatetime' => 'int',
        'status' => 'int',
        'image' => 'string',
        'sub_name' => 'string',
        'content1' => 'text',
        'content2' => 'text',
        'content3' => 'text',
        'content4' => 'text',
        'content5' => 'text',
        'content6' => 'text',
    ];

    public function getStatusList()
    {
        return ['30' => __('Status 30')];
    }

    public function getStatusTextAttr($value, $data)
    {
        $value = $value ?: ($data['status'] ?? '');
        $list = $this->getStatusList();
        return $list[$value] ?? '';
    }

    /**
     * 获取树形结构数据（优化版本）
     * @param array $where 查询条件
     * @param int $cacheTime 缓存时间
     * @return array
     */
    public function getTreeData($where = [], $cacheTime = 300)
    {
        // 使用简单的缓存键，避免序列化问题
        $cacheKey = 'cate_tree_' . md5(count($where));
        $data = Cache::get($cacheKey);
        
        if (!$data) {
            $data = $this->field('id,pid,name,sort,status,sub_name')
                ->where($where)
                ->order(['sort' => 'asc', 'id' => 'asc'])
                ->select();
            
            Cache::set($cacheKey, $data, $cacheTime);
        }
        
        return $data;
    }

    /**
     * 清除相关缓存
     */
    public function clearCache()
    {
        Cache::rm('cate_tree_*');
        Cache::rm('cate_tree_data');
        Cache::rm('cate_tree_list_*');
    }

    /**
     * 模型事件：数据变更时清除缓存
     */
    protected static function init()
    {
        self::afterWrite(function ($model) {
            $model->clearCache();
        });
        
        self::afterDelete(function ($model) {
            $model->clearCache();
        });
    }
}
